package j2.shopmail.ui.dashboard;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import j2.shopmail.*;

import java.util.ArrayList;
import java.util.List;

public class DashboardFragment extends Fragment
{
   public static List<OrderGood> orderGoods=new ArrayList<>();
    public  static void UpdataTotalPrice()
    {
        double p=0;
        for(int i=0;i<DashboardFragment.orderGoods.size();i++)
            p+=DashboardFragment.orderGoods.get(i).getCount()*Find(DashboardFragment.orderGoods.get(i).getGoodID()).Price;
        price.setText("总价:"+ String .format("%.2f",p)+"元");
    
    }
    private DashboardViewModel dashboardViewModel;
 static ListView listView;
 static Button submit;
 static TextView price;
   public static Goods Find(String id)
    {
        for(int i=0;i< Goods.NowGoods.size();i++)
        {
            if(Goods.NowGoods.get(i).ID.trim().equals(id.trim()))
                return Goods.NowGoods.get(i);
        }
        return new Goods();
    }
    
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
      listView=  root.findViewById(R.id.crat);
      listView.setAdapter(new CartADP());
      submit=root.findViewById(R.id.createOrder);
      final EditText p=root.findViewById(R.id.userphone);
        final EditText a=root.findViewById(R.id.useraddress);
      submit.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v)
          {
           AsycHttp<String,String> http=new AsycHttp<>();
           http.setBackgroundAction(new AsycHttpAction<String, String>() {
               @Override
               public String BackGroundAction(String... params)
               {
                   if(MainActivity.user.isLogin)
                   {
                       
                       String c=ServerHelper.MakeCreateOrderStr(MainActivity.user.name,p.getText().toString(),a.getText().toString());
                       JSONArray object=(JSONArray) JSON.toJSON(DashboardFragment.orderGoods);
    
                       return HttpHelper.Post(object.toJSONString(),c);
                   }
                   return "-1";

               }
    
               @Override
               public void ProgressUpdateAction(View UI, Double... values)
               {
        
               }
    
               @Override
               public void ResultFunction(String result)
               {
                   if(result.equals("-1"))
                       Toast.makeText(MainActivity.Self,"请先登录",Toast.LENGTH_SHORT).show();
                   else
                   Toast.makeText(MainActivity.Self,result.trim().equals("1")?"订单创建成功":"订单创建失败", Toast.LENGTH_SHORT).show();
               }
    
               @Override
               public void PreDoFunction()
               {
        
               }
           });
           http.execute();
          }
      });
        price=root.findViewById(R.id.total);
        UpdataTotalPrice();
        return root;
    }
}
class CartADP extends BaseAdapter
{
    
    @Override
    public int getCount()
    {
        return DashboardFragment.orderGoods.size();
    }
    
    @Override
    public Object getItem(int position)
    {
        return DashboardFragment.orderGoods.get(position);
    }
    
    @Override
    public long getItemId(int position)
    {
        return position;
    }
    
    private  void ChangeCount(int changevalue,TextView item)
    {
        if(!(Boolean)(item.getTag(R.id.tag_isout)))
        {
            OrderGood o= (OrderGood) item.getTag(R.id.tag_order);
        
            if(o.getCount()>0)
                o.setCount(o.getCount()+changevalue);
            if(o.getCount()==0)
            {
                DashboardFragment.orderGoods.remove(o);
                this.notifyDataSetChanged();
            }

            
            Goods g = (Goods) item.getTag(R.id.tag_good);
            OrderGood baseInfo=(OrderGood) item.getTag(R.id.tag_order);
            item.setText("品名："+g.Name+";\n价格："+g.Price+"元\n个数:"+baseInfo.getCount());
        
        }
        else
        {
            OrderGood o= (OrderGood) item.getTag(R.id.tag_order);
            o.setCount(0);
            Goods g = (Goods) item.getTag(R.id.tag_good);
            OrderGood baseInfo=(OrderGood) item.getTag(R.id.tag_order);
            item.setText("品名："+g.Name+";\n价格："+g.Price+"元\n个数:"+baseInfo.getCount());
        }
        DashboardFragment.UpdataTotalPrice();
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        final View view= LayoutInflater.from(MainActivity.Self).inflate(R.layout.orderlistitem, null);
        final TextView textView=view.findViewById(R.id.iteminfo);
        OrderGood baseInfo= DashboardFragment.orderGoods.get(position);
      Goods g= DashboardFragment.Find(baseInfo.getGoodID());
      if(g!=null)
      {
          textView.setText("品名："+g.Name+";\n价格："+g.Price+"元\n个数:"+baseInfo.getCount());
          textView.setTag(R.id.tag_order,baseInfo);
          textView.setTag(R.id.tag_good,g);
          textView.setTag(R.id.tag_isout, false);
        ImageView imageView=  view.findViewById(R.id.orderimage);
        imageView.setImageBitmap(g.Image);
      }
      else
      {
          textView.setText("商品ID："+baseInfo.getGoodID()+"，已下架");
          textView.setTag(R.id.tag_order, baseInfo);
          textView.setTag(R.id.tag_isout, true);
      }
      Button button=view.findViewById(R.id.LessBtn);
      button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v)
          {
        ChangeCount(-1, textView);
          }
      });
      button=view.findViewById(R.id.moreBtn);
      button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v)
          {
        ChangeCount(1, textView);
          }
      });
        return view;
    }

    
}